package leetcode_day._2022._202203._1120;

import general_class.Node;

import java.util.*;

/**
 * @author yzh
 * @version 1.0
 * @date 2022/3/12 11:30
 * N 叉树的后序遍历
 * 算法：递归、迭代
 */
public class _12_590 {

    List<Integer> ans;

    public List<Integer> postorder_iterator(Node root) {
        ans = new ArrayList<>();
        if (root == null) return ans;
        Deque<Node> stack = new LinkedList<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node pop = stack.pop();
            ans.add(pop.val);
            for (Node child : pop.children) stack.push(child);
        }
        Collections.reverse(ans);
        return ans;
    }

    public List<Integer> postorder(Node root) {
        ans = new ArrayList<>();
        dfs(root);
        return ans;
    }
    public void dfs(Node node) {
        if (node == null) return;
        for (Node child : node.children) dfs(child);
        ans.add(node.val);
    }

}
